package com.kanche.bigbaby.collection;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;

import com.kanche.bigbaby.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;

//import com.kkche.merchant.awesome.DrawableAwesome;
//import com.kkche.merchant.domain.Consts;
//import com.kkche.merchant.http.MerchantService;
//import com.kkche.merchant.utils.CapturePhotoUtils;

/**
 * Created by nealmi on 8/12/14.
 */

public class GalleryChooserActivity extends BaseActivity {
    private static final int MAX = 24;
    private int limitation = MAX;
    private static final String TAG = "Merchant:GalleryChooserActivity";
    private GridView gridView;
    private Button doneButton;
    private LazyCursorAdapter adapter;
    private ArrayList<CharSequence> selectedPaths;
    private Uri capturedPhotoUri;
    private Intent photoService;
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery_chooser);

        toolbar = justFindIt(R.id.toolbar);
        toolbar.setTitle("选择照片");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        limitation = getIntent().getIntExtra("limitation", MAX);
        selectedPaths = getIntent().getCharSequenceArrayListExtra("selectedPaths");
        if (selectedPaths == null)
            selectedPaths = new ArrayList<CharSequence>();
        gridView = (GridView) findViewById(R.id.gridView);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Img img = (Img) parent.getItemAtPosition(position);
                adapter.toggle(img);
//                if (limitation == 1 && adapter.getCheckedCount() == 1) {
//                    done();
//                    return;
//                }
                if (adapter.getCheckedCount() <= limitation) {
                    doneButton.setText("完成(" + adapter.getCheckedCount() + ")");
                } else {
                    adapter.toggle(img);
                    Guard.showMessage(GalleryChooserActivity.this, "最多可以选择" + limitation + "项");
                }
            }
        });
        doneButton = (Button) findViewById(R.id.doneButton);
        doneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                done();
            }
        });
//        MediaScannerConnection.scanFile(this,
//                new String[]{Environment.getExternalStoragePublicDirectory(
//                        Environment.DIRECTORY_DCIM).toString()}, null,
//                new MediaScannerConnection.OnScanCompletedListener() {
//                    public void onScanCompleted(String path, Uri uri) {
//                        loadImagesFromGallery();
//                    }
//                });
//        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
//                Uri.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
        loadImagesFromGallery();
    }

    private void done() {
        Intent data = new Intent();
        data.putCharSequenceArrayListExtra("paths", adapter.getCheckedImgPaths());
        setResult(RESULT_OK, data);
        finish();
        adapter.cleanUp();
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.gallery_chooser_menu, menu);
//        MenuItem item = menu.findItem(R.id.action_take_photo);
//        DrawableAwesome cameraIcon = new DrawableAwesome.DrawableAwesomeBuilder(this, R.string.fa_camera).build();
//        item.setIcon(cameraIcon);
//        return super.onCreateOptionsMenu(menu);
//    }
//
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            finish();
        }
//        if (item.getItemId() == R.id.action_take_photo) {
//
//
//            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            capturedPhotoUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedPhotoUri); // set the image file name
//            // start the image capture Intent
//            startActivityForResult(intent, Consts.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
//            photoService = new Intent();
//            photoService.setAction("com.kkche.merchant.photoservice");
//            startService(photoService);
//
//            return true;
//        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == Consts.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
//            String capturePath = capturedPhotoUri.getPath();
//            Img img = queryImageByUrl(capturePath);
//            if (img == null) {
//                String url = CapturePhotoUtils.insertImage(getContentResolver(), capturePath, "", "");
//                if (StringUtils.hasText(url)) {
//                    long id = ContentUris.parseId(Uri.fromFile(new File(url)));
//                    img = queryImageById(id);
//                }
//            }
//
//            if (img != null) {
//                adapter.addChecked(img);
//                doneButton.setText("完成(" + adapter.getCheckedCount() + ")");
//                //new File(capturePath).delete();
//                capturedPhotoUri = null;
//                loadImagesFromGallery();
//                return;
//            }
//
//            Guard.showMessage(this, R.string.error_take_photo);
//        }
//    }

    private Img queryImageById(long id) {
        String[] projection = {MediaStore.Images.Media.DATA};
        String selection = MediaStore.Images.Media._ID + " = " + id;
        String[] selectionArgs = null;
        String sortOrder = null;
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, selection, selectionArgs, sortOrder);
        if (cursor.moveToNext()) {
            return Img.create(id, cursor.getString(0));
        }
        return null;
    }

    private Img queryImageByUrl(String url) {
        String[] projection = {MediaStore.Images.Media._ID};
        String selection = MediaStore.Images.Media.DATA + " = '" + url + "'";
        String[] selectionArgs = null;
        String sortOrder = null;
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, selection, selectionArgs, sortOrder);
        if (cursor.moveToNext()) {
            return Img.create(cursor.getLong(0), url);
        }
        return null;
    }

    private void loadImagesFromGallery() {
        // Query for all images on external storage
        String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_MODIFIED};
        String selection = MediaStore.Images.Media.DATA + " not in (";
        for (CharSequence selectedPath : selectedPaths) {
            selection += "'" + selectedPath + "',";
        }
        selection += "'')";

        String[] selectionArgs = null;
        String sortOrder = MediaStore.Images.Media.DATE_MODIFIED + " DESC";
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, selection, selectionArgs, sortOrder);
        if (adapter == null) {
            adapter = new LazyCursorAdapter(this, cursor);
            gridView.setAdapter(adapter);
        } else {
            adapter.refresh(cursor);
        }
    }

    public static class LazyCursorAdapter extends BaseAdapter {
        private Cursor cursor;
        private Context context;
        private Set<Img> checkedImgs = new LinkedHashSet<Img>();
        private Holder holder = new Holder();

        public LazyCursorAdapter(Context context, Cursor cursor) {
            this.cursor = cursor;
            this.context = context;

        }

        @Override
        public int getCount() {
            if (cursor.isClosed()) {
                return 0;
            }
            return cursor.getCount();
        }

        private void addChecked(Img img) {
            checkedImgs.add(img);
        }

        private void removeChecked(Img img) {
            checkedImgs.remove(img);
        }

        @Override
        public Object getItem(int position) {
            cursor.moveToPosition(position);
            long rowId = cursor.getLong(0);
            String thumb = cursor.getString(1);

            return Img.create(rowId, thumb);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.gallery_chooser_item, null);

            }
            holder = new Holder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
            holder.cover = convertView.findViewById(R.id.cover);

            Img img = (Img) getItem(position);
            String path = img.path;


//            String selection = MediaStore.Images.Thumbnails.IMAGE_ID + "= ?";
//            String[] selectionArgs = new String[]{img.rowId + ""};
//            String[] projection = {MediaStore.Images.Thumbnails.DATA};
//
//            MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), img.rowId, MediaStore.Images.Thumbnails.MICRO_KIND, null);
//
//            Cursor cursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
//                    projection, selection, selectionArgs, null);
//            String path = null;
//            if (cursor.moveToNext()) {
//                path = cursor.getString(0);
//            }
//            cursor.close();

            if (StringUtils.hasText(path)) {
                int width = context.getResources().getDimensionPixelSize(R.dimen.image_thum_width);
                int height = context.getResources().getDimensionPixelSize(R.dimen.image_thum_height);
                DisplayImageOptions options = new DisplayImageOptions.Builder()
//                        .cloneFrom(MerchantService.CurrentAppConfig.smallPlaceholderOptions)
                        .preProcessor(new ImageUtils.ThumbnailImageProcessor(width, height))
//                        .considerExifParams(MerchantService.CurrentAppConfig.CONSIDER_EXIF_PARAMS)
                        .resetViewBeforeLoading(false)
                        .build();
                ImageLoader.getInstance().displayImage("file:/" + path, holder.imageView, options);

//                Picasso.with(context).load(new File(path))
//                        .placeholder(R.drawable.place_holder_small)
//                        .resizeDimen(R.dimen.image_thum_width, R.dimen.image_thum_height)
//                        .centerCrop()
//                        .into(holder.imageView);
            }
            if (checkedImgs.contains(img)) {
                holder.cover.setVisibility(View.VISIBLE);
            } else {
                holder.cover.setVisibility(View.GONE);
            }
            return convertView;
        }

        public void toggle(Img img) {
            if (checkedImgs.contains(img)) {
                removeChecked(img);
            } else {
                addChecked(img);
            }
            notifyDataSetChanged();
        }

        public int getCheckedCount() {
            return checkedImgs.size();
        }

        public void cleanUp() {
            cursor.close();
        }

        public ArrayList<CharSequence> getCheckedImgPaths() {
            ArrayList<CharSequence> paths = new ArrayList<CharSequence>();
            for (Img img : checkedImgs) {
                paths.add(img.path);
            }
            return paths;
        }

        public void refresh(Cursor cursor) {
            this.cursor = cursor;
            notifyDataSetChanged();
        }

        class Holder {
            public View cover;
            private ImageView imageView;
        }
    }

    public static class Img {
        long rowId;
        String path;

        private Img(long rowId, String path) {
            this.rowId = rowId;
            this.path = path;
        }

        public static Img create(long rowId, String path) {
            return new Img(rowId, path);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Img img = (Img) o;

            if (rowId != img.rowId) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return (int) (rowId ^ (rowId >>> 32));
        }
    }

    @Override
    protected void onDestroy() {
        if(null != photoService){
            stopService(photoService);
        }
        super.onDestroy();
    }
}
